package aspirecn.project3.service.impl;


import aspirecn.project3.manager.UserManager;
import aspirecn.project3.model.LoginUser;
import aspirecn.project3.model.PageVo;
import aspirecn.project3.model.RespPageBean;
import aspirecn.project3.model.User;
import aspirecn.project3.service.UserService;
import aspirecn.project3.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

import static aspirecn.project3.constant.RedisKey.REDIS_USER_TOKEN;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UserManager userManager;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private RedisOperator redisOperator;

    @Override
    public JsonData addUser(User user) {
        if (!CheckUtil.isPhone(user.getPhone())) {
            return JsonData.buildError("手机输入格式错误！");
        }
        if (!CheckUtil.isEmail(user.getEmail())) {
            return JsonData.buildError("邮箱输入格式错误！");
        }
        return userManager.addUser(user);
    }

    @Override
    public JsonData login(String username, String password) {
        User userByUsername = userManager.getUserByUsername(username);
        log.info("{}", userByUsername);
        if (userByUsername == null) {
            return JsonData.buildError("该用户不存在");
        } else {
            log.info("{}", userByUsername.getStatus());
            if (userByUsername.getStatus().equals("禁用")) {
                return JsonData.buildError("该账号已被禁用,请联系管理员");
            } else if (!userByUsername.getType().equals("管理员")) {
                return JsonData.buildError("该账号无权限登录,请联系管理员");
            } else {
                if (passwordEncoder.matches(password, userByUsername.getPassword())) {
                    // if (userByUsername.getPassword().equalsIgnoreCase(password)) {
                    //1. 保留关键用户信息
                    LoginUser loginUser = new LoginUser();
                    BeanUtils.copyProperties(userByUsername, loginUser);
                    // 2. 实现用户的redis会话
//                    String uniqueToken = UUID.randomUUID().toString().trim();
                    String uniqueToken = JWTUtil.geneJsonWebToken(loginUser);
                    loginUser.setUserUniqueToken(uniqueToken);
                    redisOperator.set(REDIS_USER_TOKEN + ":" + loginUser.getId(),
                            JsonUtil.objectToJson(loginUser));
                    return JsonData.buildSuccess(loginUser);
                } else {
                    return JsonData.buildError("密码错误,请重新输入密码");
                }
            }
        }
    }
    @Override


    public JsonData logout(int userId) {
        redisOperator.del(REDIS_USER_TOKEN + ":" + userId);
        return JsonData.buildSuccess("退出登录成功");
    }

    @Override
    public User getRandomUser() {
        return userManager.getRandomUser();
    }

    @Override
    public JsonData getUserByName(Integer page, Integer size, String keyword) {
        if (page != null && size != null) {
            page = (page - 1) * size;
        }
        List<User> data = userManager.getUserByName(page, size, keyword);
        return getJsonData(page, size, data);
    }

    @Override
    public Integer insertUser(User user) {
        return userManager.insertUser(user);
    }

    @Override
    public User getUserById(Integer id) {
        return userManager.getUserById(id);
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return userManager.deleteByPrimaryKey(id);
    }

    @Override
    public JsonData getUserByPage(Integer page, Integer size) {
        if (page != null && size != null) {
            page = (page - 1) * size;
        }
        List<User> data = userManager.getUserByPage(page, size);
        return getJsonData(page, size, data);
    }

    @Override
    public int alterUser(User user) {
        return userManager.alterUser(user);
    }

    private JsonData getJsonData(Integer page, Integer size, List<User> data) {
        Long total = userManager.getTotal();
        PageVo<List<User>> pageVo = new PageVo<>();
        pageVo.setData(data);
        pageVo.setTotal(total);
        pageVo.setPage(Long.valueOf(page));
        pageVo.setLimit(Long.valueOf(size));
        return JsonData.buildSuccess(pageVo);
    }
}
